﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace TestWinClient
{
    /// <summary>
    /// 
    /// </summary>
    public class UpdaterHelper
    {
        /// <summary>
        /// 
        /// </summary>
        private static string UpdateExeName
        {
            get 
            {
                string exeName = ConfigurationManager.AppSettings["UpdateExe"];
                if (exeName != null)
                {
                    exeName = exeName.Trim();
                }
                return exeName;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private static string UpdateExeFullPathName
        {
            get
            {
                string pathName = Path.Combine(Application.StartupPath, UpdateExeName);
                return pathName;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static int CheckNewFiles()
        {
            return RunUpdater("-checkforupdates", true);
        }

        /// <summary>
        /// 
        /// </summary>
        public static void RunUpdater()
        {
            RunUpdater("-run", false);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="arguments"></param>
        /// <param name="waitForExit"></param>
        /// <returns></returns>
        private static int RunUpdater(string arguments, bool waitForExit)
        {
            FileInfo info = new FileInfo(UpdateExeFullPathName);
            if (!info.Exists)
            {
                if (!string.IsNullOrEmpty(UpdateExeName))
                {
                    //throw new ApplicationException("更新程序 " + UpdateExeName + " 不存在");
                }
                return 0;
            }

            ProcessStartInfo info2 = new ProcessStartInfo();
            info2.FileName = info.FullName;
            if (info.Directory != null)
            {
                info2.WorkingDirectory = info.Directory.FullName;
            }
            info2.Arguments = arguments;
            Process process = new Process();
            process.StartInfo = info2;
            process.Start();
            if (!waitForExit)
            {
                return 0;
            }
            process.WaitForExit();
            return process.ExitCode;
        }


    }
}
